package com.xmy.aboutThread;

// 等待 通知机制 wait notify
public class Demo4 {

    private static Object lock = new Object();

    private static int num = 0;

    static class ThreadA implements Runnable {

        @Override
        public void run() {

            synchronized (lock) {

                for (int i = 0; i < 10; i++) {

                    System.out.println("ThreadA " + num);

                    num++;

                    lock.notify();

                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                lock.notify();
            }
        }
    }

    static class ThreadB implements Runnable {

        @Override
        public void run() {

            synchronized (lock) {

                for (int i = 0; i < 10; i++) {

                    System.out.println("ThreadB " + num);
                    num++;
                    lock.notify();

                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                lock.notify();
            }
        }
    }



    public static void main(String[] args) throws InterruptedException {

        new Thread(new ThreadA()).start();

        Thread.sleep(20);

        new Thread(new ThreadB()).start();

    }
}


